import { useEffect, useRef, useState } from "react"
import * as echarts from 'echarts';
import { useSelector } from "react-redux";
import { State } from "@/redux/interface";

interface EchartsProps {
    option: echarts.EChartsCoreOption
}

/**
 * @description 封装 echarts
 */
const Echarts = (props:EchartsProps) => {
    const echartsRef = useRef<HTMLDivElement>(null)
    const {option} = props
    const myChart:{
        current: echarts.EChartsType | null
    } = {
        current:null
    }
    const {theme} = useSelector((state:State) => state.global)

    // 初始化
    useEffect(() => {
        if(myChart.current) {
            myChart.current?.dispose()
        }
        if(echartsRef.current) {
            let echartsTheme = ""
            switch(theme) {
                case "default":
                    echartsTheme = ""
                    break;
                case "dark":
                    echartsTheme = "dark"
                    break;
            }
           const instance = echarts.init(echartsRef.current, echartsTheme)
           myChart.current = instance
           myChart.current?.setOption(option)
        }
    },[echartsRef, theme])

    // 重新渲染option
    useEffect(() => {
        if(myChart.current) {
            myChart.current?.setOption(option)
        }
    },[option,myChart])

    // 容器大小变化
    const echartsResize = () => {
        myChart.current?.resize()
    }

    useEffect(() => {
        window.addEventListener("resize", echartsResize, false)
        return () => {
            window.removeEventListener("resize", echartsResize)
            myChart.current?.dispose()
        }
    },[])

    return (
        <div ref={echartsRef} style={{width:'100%',height:'100%'}}></div>
    )
}

export default Echarts